package net.qhzw.vip.qiyu.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 未接单
 */
@SpringBootConfiguration
public class DistriOrderTtlQueueConfig {

    //普通交换机的名称
    public final static String DISTRI_ORDER_EXCHANGE = "DISTRI_ORDER_EXCHANGE";
    //死信交换机的名称
    public final static String DISTRI_ORDER_DEAD_LETTER_EXCHANGE = "DISTRI_ORDER_DEAD_LETTER_EXCHANGE";
    //普通队列的名称
    public final static String QUEUE_DISTRI_ORDER = "QUEUE_DISTRI_ORDER";
    //死信队列的名称
    public final static String DEAD_LETTER_QUEUE_DISTRI_ORDER = "DEAD_LETTER_QUEUE_DISTRI_ORDER";

    //声明交换机 distriOrderExchange
    @Bean("distriOrderExchange")
    public DirectExchange distriOrderExchange(){
        return new DirectExchange(DISTRI_ORDER_EXCHANGE);
    }
    //声明交换机 cancelOrderDeadLetterExchange
    @Bean("distriOrderDeadLetterExchange")
    public DirectExchange distriOrderDeadLetterExchange(){
        return new DirectExchange(DISTRI_ORDER_DEAD_LETTER_EXCHANGE);
    }

    //声明普通队列 TTL
    @Bean("queueDistriOrder")
    public Queue queueDistriOrder(){
        //正常队列绑定死信交换机信息，因为正常队列消息会变为死信
        Map<String, Object> arguments = new HashMap<>();
        //正常队列设置死信交换机 参数 key 是固定值
        arguments.put("x-dead-letter-exchange",DISTRI_ORDER_DEAD_LETTER_EXCHANGE);
        //正常队列设置死信 routing-key 参数 key 是固定值
        arguments.put("x-dead-letter-routing-key", "DISTRI_ORDER");
        //设置过期时间 10s,单位是ms，可以在消费者正常队列处设置，也可以在生产者发送处设置
        arguments.put("x-message-ttl",1000 * 60 * 2);
        return QueueBuilder.durable(QUEUE_DISTRI_ORDER).withArguments(arguments).build();
    }

    //声明死信队列
    @Bean("deadLetterQueueDistriOrder")
    public Queue deadLetterQueueDistriOrder(){
        //没有参数
        return QueueBuilder.durable(DEAD_LETTER_QUEUE_DISTRI_ORDER).build();
    }

    //五大组件完毕，开始互相绑定
    @Bean
    public Binding queueDistriOrderBindingDistriOrderExchange(@Qualifier("queueDistriOrder") Queue queueDistriOrder,
                                  @Qualifier("distriOrderExchange") DirectExchange distriOrderExchange){
        //将 X 正常交换机和 QA 队列 绑定
        return BindingBuilder.bind(queueDistriOrder).to(distriOrderExchange).with("distriOrder");
    }

    @Bean
    public Binding deadLetterQueueDistriOrderBindingDistriOrderDeadLetterExchange(@Qualifier("deadLetterQueueDistriOrder") Queue deadLetterQueueDistriOrder,
                                  @Qualifier("distriOrderDeadLetterExchange") DirectExchange distriOrderDeadLetterExchange){
        //将 Y 死信交换机和 QD 死信队列 绑定
        return BindingBuilder.bind(deadLetterQueueDistriOrder).to(distriOrderDeadLetterExchange).with("DISTRI_ORDER");
    }

}
